<template>
    <div class="novel-container">
        <PageHeader title="小说资源" />
        <div class="novel-list">
            <MovieCard v-for="novel in novels.records" :key="novel.id" :id="novel.id" :title="novel.title"
                :image="novel.coverImage" :author="novel.author" :description="novel.description" rating=0
                :genre="novel.category" @click="navigateToReader(String(novel.id))" />
        </div>
        <div class="pagination" v-if="novels.total > 0">
            <button @click="changePage(currentPage - 1)" :disabled="currentPage <= 1">上一页</button>
            <span>{{ currentPage }} / {{ totalPages }}</span>
            <button @click="changePage(currentPage + 1)" :disabled="currentPage >= totalPages">下一页</button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import type { Novel } from '@/dataType/novelType';
import type { PageResponse } from '@/dataType/pageType';
import { novelService } from '../../services/novelService';
import MovieCard from '@/components/MovieCard.vue';
import PageHeader from '@/components/PageHeader.vue';

const router = useRouter();
const novels = ref<PageResponse<Novel>>({ records: [], total: 0, current: 1, size: 10 });
const currentPage = ref(1);
const pageSize = ref(10);

const totalPages = computed(() => Math.ceil(novels.value.total / pageSize.value));

const fetchNovels = async () => {
    novels.value = await novelService.getNovelList(currentPage.value, pageSize.value);
};

const changePage = (page: number) => {
    if (page >= 1 && page <= totalPages.value) {
        currentPage.value = page;
        fetchNovels();
    }
};

const navigateToReader = (novelId: string) => {
    router.push({ name: 'NovelReader', params: { novelId } });
};

onMounted(() => {
    fetchNovels();
});
</script>

<style scoped>
.novel-container {
    padding: 20px;
}

.page-header {
    margin-bottom: 24px;
}

.novel-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 15px;
    margin-top: 20px;
}

.pagination button {
    padding: 8px 16px;
    border: 1px solid #ddd;
    border-radius: 4px;
    background-color: #fff;
    cursor: pointer;
}

.pagination button:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}
</style>